<?php
// upload.php

// Ensure the uploads directory exists
if (!file_exists('uploads')) {
    mkdir('uploads', 0755, true);
}

// Check if a file was uploaded
if (isset($_FILES['upload'])) {
    $file = $_FILES['upload'];

    // Validate the file (e.g., check file type and size)
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    $maxFileSize = 5 * 1024 * 1024; // 5MB

    if (in_array($file['type'], $allowedTypes) && $file['size'] <= $maxFileSize) {
        // Generate a unique filename
        $filename = uniqid() . '_' . basename($file['name']);
        $filepath = 'uploads/' . $filename;

        // Move the uploaded file to the uploads directory
        if (move_uploaded_file($file['tmp_name'], $filepath)) {
            // Return the file URL to CKEditor 5
            $response = [
                'default' => $filepath
            ];
            echo json_encode($response);
            exit;
        }
    }

    // If the upload fails, return an error
    $response = [
        'error' => [
            'message' => 'File upload failed. Please check the file type and size.'
        ]
    ];
    echo json_encode($response);
    exit;
}